<template>
  <div class="page-content">
    <!--    搜索框-->
    <el-row>
      <el-card style="width: 100%;margin-bottom: 16px">
        <div class="search-box">
          <el-input placeholder="Place input softwareName or productNo" v-model:model-value="searchQuery" clearable
                    @keydown.enter="searchSoftware(searchQuery)"></el-input>
          <el-button type="primary" @click="searchSoftware(searchQuery)"> 搜索</el-button>
        </div>
      </el-card>
    </el-row>

    <!--内容结构-->
    <el-row :gutter="20">
      <el-col :span="24">
        <order v-if="isOrder"  :data="searchResult"> </order>
        <link-table v-else :list="softwareQueryList"></link-table>
      </el-col>
    </el-row>
    <!--    token dialog-->
    <el-dialog v-model="dialogFormVisible" title="请输入Token" width="500">
      <el-form>
        <el-form-item label="Token:">
          <el-input v-model="token" autocomplete="off"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="confirmToken">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import {ElInput, ElButton, ElCard, ElRow, ElCol, ElMessage} from 'element-plus';

import {getSoftwareQueryList} from "@/api/link.ts";
import {Result, SoftwareQuery} from "@/type.ts";
import LinkTable from "@/components/LinkTable.vue";
import {getOrder} from "@/api/search.ts";
import Order from "@/components/order.vue";
const dialogFormVisible = ref(false)

const searchQuery = ref('');
const isOrder =ref(false)
const softwareQueryList = ref<SoftwareQuery[]>();
const token = ref<string>("")


const searchSoftware = (softwareName: string) => {
  if (!softwareName){
    ElMessage.error("The input cannot be empty")
    return
  }
  if (isNumeric(softwareName)){
    getOrder(softwareName).then(res => {
      if (res.code == 403) {
        ElMessage.error(res.msg)
        dialogFormVisible.value = true
        return
      }
      searchResult.value = res.data
    })
    isOrder.value =true
  }else {
    getSoftwareQueryList(softwareName).then((res) => {
      softwareQueryList.value = res.rows as SoftwareQuery[]
    })
    isOrder.value =false
  }

};
function confirmToken() {
  dialogFormVisible.value = false
  localStorage.setItem("search_token", token.value)
  // 刷新页面，保证缓存生效
  location.reload()
}
const searchResult = ref<Result>()



function isNumeric(str: string): boolean {
  const numericPattern = /^\d+$/;
  return numericPattern.test(str);
}

</script>

<style scoped>

.page-content {
  width: 70%;
  height: 100%;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
}

.search-box {
  width: 100%;
  height: 100%;
  display: flex;
  gap: 10px;
  flex-direction: row;
}

</style>
